import React from 'react';
import {
  Box,
  Container,
  Paper,
  Typography,
  TextField,
  Button,
  Link,
  Alert,
  useTheme
} from '@mui/material';
import { useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { useNavigate, Link as RouterLink } from 'react-router-dom';
import { useRegisterMutation } from '../../store/services/auth';
import Loading from '../../components/common/Loading';

interface RegisterForm {
  username: string;
  email: string;
  password: string;
  confirmPassword: string;
}

const Register: React.FC = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const theme = useTheme();
  const [register, { isLoading, error }] = useRegisterMutation();

  const {
    register: registerField,
    handleSubmit,
    watch,
    formState: { errors }
  } = useForm<RegisterForm>({
    defaultValues: {
      username: '',
      email: '',
      password: '',
      confirmPassword: ''
    }
  });

  const password = watch('password');

  const onSubmit = async (data: RegisterForm) => {
    try {
      await register({
        username: data.username,
        email: data.email,
        password: data.password
      }).unwrap();

      // 注册成功后跳转到登录页
      navigate('/login', { state: { registered: true } });
    } catch (err) {
      console.error('Registration failed:', err);
    }
  };

  if (isLoading) {
    return <Loading />;
  }

  return (
    <Container component="main" maxWidth="xs">
      <Box
        sx={{
          marginTop: 8,
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
        }}
      >
        <Paper
          elevation={3}
          sx={{
            p: 4,
            width: '100%',
            borderRadius: 2,
            bgcolor: 'background.paper'
          }}
        >
          <Typography component="h1" variant="h5" align="center" gutterBottom>
            {t('auth.register.title')}
          </Typography>

          {error && (
            <Alert severity="error" sx={{ mb: 2 }}>
              {t('auth.register.error')}
            </Alert>
          )}

          <Box component="form" onSubmit={handleSubmit(onSubmit)} sx={{ mt: 1 }}>
            <TextField
              margin="normal"
              required
              fullWidth
              id="username"
              label={t('auth.register.username')}
              autoComplete="username"
              autoFocus
              error={!!errors.username}
              helperText={errors.username?.message}
              {...registerField('username', {
                required: t('auth.register.usernameRequired'),
                minLength: {
                  value: 3,
                  message: t('auth.register.usernameMinLength')
                },
                pattern: {
                  value: /^[a-zA-Z0-9_-]+$/,
                  message: t('auth.register.usernamePattern')
                }
              })}
            />

            <TextField
              margin="normal"
              required
              fullWidth
              id="email"
              label={t('auth.register.email')}
              autoComplete="email"
              error={!!errors.email}
              helperText={errors.email?.message}
              {...registerField('email', {
                required: t('auth.register.emailRequired'),
                pattern: {
                  value: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
                  message: t('auth.register.emailInvalid')
                }
              })}
            />

            <TextField
              margin="normal"
              required
              fullWidth
              id="password"
              label={t('auth.register.password')}
              type="password"
              autoComplete="new-password"
              error={!!errors.password}
              helperText={errors.password?.message}
              {...registerField('password', {
                required: t('auth.register.passwordRequired'),
                minLength: {
                  value: 6,
                  message: t('auth.register.passwordMinLength')
                }
              })}
            />

            <TextField
              margin="normal"
              required
              fullWidth
              id="confirmPassword"
              label={t('auth.register.confirmPassword')}
              type="password"
              autoComplete="new-password"
              error={!!errors.confirmPassword}
              helperText={errors.confirmPassword?.message}
              {...registerField('confirmPassword', {
                required: t('auth.register.confirmPasswordRequired'),
                validate: value =>
                  value === password || t('auth.register.passwordMismatch')
              })}
            />

            <Button
              type="submit"
              fullWidth
              variant="contained"
              sx={{ mt: 3, mb: 2 }}
              disabled={isLoading}
            >
              {t('auth.register.submit')}
            </Button>

            <Box sx={{ textAlign: 'center' }}>
              <Link
                component={RouterLink}
                to="/login"
                variant="body2"
                color="primary"
              >
                {t('auth.register.login')}
              </Link>
            </Box>
          </Box>
        </Paper>
      </Box>
    </Container>
  );
};

export default Register; 